package com.android.manghe.market.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.android.base.tools.DisplayUtil;
import com.android.base.tools.Glide.GlideHelper;
import com.android.manghe.R;
import com.android.manghe.market.adapter.multi.CartGoodLevel;
import com.android.manghe.market.adapter.multi.CartRecommendLevel;
import com.android.manghe.market.model.CartGoodListRes;
import com.android.manghe.view.AutoHeightGridLayoutManager;
import com.android.manghe.view.AutoHeightLayoutManager;
import com.android.manghe.view.GridAuctionSpacesItemDecoration;
import com.android.manghe.view.dialog.InputGoodQtyDialog;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.util.ArrayList;
import java.util.List;

public class CartPageAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {
    private Context context;
    private IModifyCallBack callBack;
    private boolean isSelectedAll;
    private boolean isEditMode;

    public CartPageAdapter(Context context, List<MultiItemEntity> data) {
        super(data);
        this.context = context;
        addItemType(0, R.layout.item_cart_good_list);
        addItemType(1, R.layout.item_cart_recommend_list);


    }

    public void setListener(IModifyCallBack callBack) {
        this.callBack = callBack;
    }

    public boolean toggleSelectedAll() {
        isSelectedAll = !isSelectedAll;
        List<CartGoodListRes.DataBean.CartGoodsBean> goodList = ((CartGoodLevel) getData().get(0)).goodList;
        for (int i = 0; i < goodList.size(); i++) {
            goodList.get(i).isSelected = isSelectedAll;
        }
        setData(0, new CartGoodLevel(goodList));
        refreshStatisticsData(goodList);
        return isSelectedAll;
    }

    public void setEditMode(boolean isEdit) {
        isEditMode = isEdit;
        notifyItemChanged(0);
    }

    public List<CartGoodListRes.DataBean.CartGoodsBean> getSelectedCartGoodList() {
        List<CartGoodListRes.DataBean.CartGoodsBean> selectedGoodList = new ArrayList<>();
        List<CartGoodListRes.DataBean.CartGoodsBean> allGoodList = ((CartGoodLevel) getData().get(0)).goodList;
        for (CartGoodListRes.DataBean.CartGoodsBean good : allGoodList) {
            if (good.isSelected) {
                selectedGoodList.add(good);
            }
        }
        return selectedGoodList;
    }

    /**
     * 更新统计数据
     */
    private void refreshStatisticsData(List<CartGoodListRes.DataBean.CartGoodsBean> goodList) {
        List<CartGoodListRes.DataBean.CartGoodsBean> resultGoodList = new ArrayList<>();
        double totalPrice = 0;
        for (CartGoodListRes.DataBean.CartGoodsBean good : goodList) {
            if (good.isSelected) {
                totalPrice += good.qty * good.goods_price;
                resultGoodList.add(good);
            }
        }
        callBack.onModified(resultGoodList, totalPrice);
    }

    public interface IModifyCallBack {
        void onModified(List<CartGoodListRes.DataBean.CartGoodsBean> selectedGoodList,
                        double totalPrice);

        void onDelete(String id);

        void modifyGoodNum(String goodId, int num, String spec, boolean isSelected);
    }

    @Override
    protected void convert(final BaseViewHolder holder, final MultiItemEntity item) {
        switch (holder.getItemViewType()) {
            case 0:
                final CartGoodLevel titleLevel = (CartGoodLevel) item;
                RecyclerView goodRecyclerView = holder.getView(R.id.goodRecyclerView);
                goodRecyclerView.setLayoutManager(new AutoHeightLayoutManager(context));
                CartGoodListAdapter goodAdapter = new CartGoodListAdapter(titleLevel.goodList, context, isEditMode);
                goodRecyclerView.setAdapter(goodAdapter);
                goodAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    CartGoodListRes.DataBean.CartGoodsBean goodInfo = titleLevel.goodList.get(position);
                    TextView tvQty = (TextView) adapter.getViewByPosition(goodRecyclerView, position, R.id.tvQuantity);
                    TextView btnQuantityMinus = (TextView) adapter.getViewByPosition(goodRecyclerView, position, R.id.btnQuantityMinus);
                    TextView btnQuantityPlus = (TextView) adapter.getViewByPosition(goodRecyclerView, position, R.id.btnQuantityPlus);
                    int quantityInt = getSelectedQuantity(tvQty);
                    switch (view.getId()) {
                        case R.id.ivDelete:
                            showDeleteDialog(goodInfo.id);
                            break;
                        case R.id.ivCheck:
                            //选中
                            //更新数据
                            goodInfo.isSelected = !goodInfo.isSelected;
                            adapter.setData(position, goodInfo);
                            refreshStatisticsData(titleLevel.goodList);
                            break;
                        case R.id.ivPic:
                            //点击图片

                            break;
                        case R.id.btnQuantityMinus:
                            //减
                            if (quantityInt > 1) {
                                String newQuantity = String.valueOf(quantityInt - 1);
                                tvQty.setText(newQuantity);
                                updateQuantityOperator(quantityInt - 1, btnQuantityMinus,
                                        btnQuantityPlus, goodInfo.goods_stock);
                                //更新数据
                                goodInfo.qty = Integer.parseInt(newQuantity);
                                adapter.setData(position, goodInfo);
                                refreshStatisticsData(titleLevel.goodList);
                                callBack.modifyGoodNum(goodInfo.goods_id, goodInfo.qty, goodInfo.spec, goodInfo.isSelected);
                            }
                            break;
                        case R.id.btnQuantityPlus:
                            //加
                            if (quantityInt < goodInfo.goods_stock) {
                                String newQuantity = String.valueOf(quantityInt + 1);
                                tvQty.setText(newQuantity);
                                updateQuantityOperator(quantityInt + 1, btnQuantityMinus,
                                        btnQuantityPlus, goodInfo.goods_stock);
                                //更新数据
                                goodInfo.qty = Integer.parseInt(newQuantity);
                                adapter.setData(position, goodInfo);
                                refreshStatisticsData(titleLevel.goodList);
                                callBack.modifyGoodNum(goodInfo.goods_id, goodInfo.qty, goodInfo.spec, goodInfo.isSelected);
                            }
                            break;
                        case R.id.tvQuantity:
                            //输入购买数量
                            InputGoodQtyDialog dialog = new InputGoodQtyDialog(context, goodInfo.qty, qty -> {
                                //更新数据
                                goodInfo.qty = qty;
                                adapter.setData(position, goodInfo);
                                refreshStatisticsData(titleLevel.goodList);
                                callBack.modifyGoodNum(goodInfo.goods_id, goodInfo.qty, goodInfo.spec, goodInfo.isSelected);
                            });
                            dialog.show();
                            break;
                        default:
                            break;
                    }
                });

                break;
            case 1:
                final CartRecommendLevel contentLevel = (CartRecommendLevel) item;
                RecyclerView recommendRecyclerView = holder.getView(R.id.recommendRecyclerView);
                recommendRecyclerView.addItemDecoration(new GridAuctionSpacesItemDecoration(DisplayUtil.dip2px(context, 8f)));
                recommendRecyclerView.setLayoutManager(new AutoHeightGridLayoutManager(context, 2));
                MarketGoodsGridAdapter recommendAdapter;
                if (contentLevel.goodList != null && !contentLevel.goodList.isEmpty()) {
                    recommendAdapter = new MarketGoodsGridAdapter(context, true,contentLevel.goodList);
                    recommendRecyclerView.setAdapter(recommendAdapter);
                }
                break;
            default:
                break;
        }
    }

    public int getSelectedQuantity(TextView tvQyt) {
        return Integer.parseInt(tvQyt.getText().toString());
    }

    private void showDeleteDialog(String id) {
        new AlertDialog.Builder(context).setMessage("确定删除该商品吗？")
                .setNegativeButton("取消", null)
                .setPositiveButton("删除", (dialogInterface, i) -> {
                    callBack.onDelete(id);
                }).show();
    }

    private void updateQuantityOperator(int newQuantity, TextView btnQuantityMinus, TextView btnQuantityPlus, int stock) {
        if (newQuantity <= 1) {
            btnQuantityMinus.setEnabled(false);
            btnQuantityPlus.setEnabled(true);
        } else if (newQuantity >= stock) {
            btnQuantityMinus.setEnabled(true);
            btnQuantityPlus.setEnabled(false);
        } else {
            btnQuantityMinus.setEnabled(true);
            btnQuantityPlus.setEnabled(true);
        }
    }

    public static class CartGoodListAdapter extends BaseQuickAdapter<CartGoodListRes.DataBean.CartGoodsBean, BaseViewHolder> {
        private Context context;
        private boolean isEditMode;
        View emptyView;

        public CartGoodListAdapter(List<CartGoodListRes.DataBean.CartGoodsBean> goodList, Context context, boolean isEditMode) {
            super(R.layout.item_cart_good, goodList);
            this.context = context;
            this.isEditMode = isEditMode;

            emptyView = LayoutInflater.from(context).inflate(R.layout.no_data, null);
            emptyView.findViewById(R.id.tvNoData).setVisibility(View.GONE);
            setEmptyView(emptyView);
        }

        @Override
        protected void convert(BaseViewHolder helper, CartGoodListRes.DataBean.CartGoodsBean item) {
            GlideHelper.load(context, item.img_src, helper.getView(R.id.ivPic));
            helper.setText(R.id.tvGoodName, item.goods_name);
            helper.setText(R.id.tvSpec, item.goods_spec);
            helper.setText(R.id.tvPrice, "￥" + item.goods_price);
            helper.setText(R.id.tvQuantity, item.qty + "");
            helper.setImageResource(R.id.ivCheck, item.isSelected ? R.mipmap.tick_click : R.mipmap.icon_tick_default);
            helper.setEnabled(R.id.btnQuantityMinus, item.qty > 1);
            helper.setEnabled(R.id.btnQuantityPlus, item.qty < item.goods_stock);
            helper.setGone(R.id.ivCheck, !isEditMode);
            helper.setGone(R.id.ivDelete, isEditMode);
            helper.addOnClickListener(R.id.ivDelete);
            helper.addOnClickListener(R.id.ivCheck);
            helper.addOnClickListener(R.id.ivPic);
            helper.addOnClickListener(R.id.btnQuantityMinus);
            helper.addOnClickListener(R.id.btnQuantityPlus);
            helper.addOnClickListener(R.id.tvQuantity);
        }
    }
}
